package com.school.hjt.schoolclasscard.ui

import android.app.AlertDialog
import android.content.*
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.util.Log
import android.view.*
import android.widget.*
import com.school.hjt.schoolclasscard.R
import com.school.hjt.schoolclasscard.db.AddData
import com.school.hjt.schoolclasscard.db.CardDao
import com.school.hjt.schoolclasscard.db.CardStudent
import com.school.hjt.schoolclasscard.db.StudentSign
import com.school.hjt.schoolclasscard.fragment.*
import com.school.hjt.schoolclasscard.model.FActivityModel
import com.school.hjt.schoolclasscard.service.LocalService
import com.school.hjt.schoolclasscard.service.RemoteService
import com.school.hjt.schoolclasscard.utlis.*
import com.school.hjt.schoolclasscard.utlis.Constant.cardStudent
import kotlinx.android.synthetic.main.activity_main2.*
import org.jetbrains.anko.imageResource
import java.util.*

class Main2Activity : AppCompatActivity() , TabLayout.OnTabSelectedListener, View.OnClickListener {
    override fun onClick(p0: View?) {
        when(p0!!.id){
            R.id.bt_close->{
                dialog!!.dismiss()
                APPUtlis.backgroundAlpha(this@Main2Activity, 1f)
            }
            R.id.tv_SchName->{
                try {
                    showLoginDialog()
                } catch (e: PackageManager.NameNotFoundException) {
                    e.printStackTrace()
                }
            }
        }
    }

    override fun onTabReselected(tab: TabLayout.Tab?) {

    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
        val img=tab!!.customView!!.findViewById<ImageView>(R.id.image)
        setIma1(img)
        val text=tab.customView!!.findViewById<TextView>(R.id.tab_item_text)
        text!!.textSize = 20f
        text.setTextColor(resources.getColor(R.color.colorMo))
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        viewpager.currentItem=tab!!.position
        val img=tab.customView!!.findViewById<ImageView>(R.id.image)
        val text=tab.customView!!.findViewById<TextView>(R.id.tab_item_text)
        text!!.textSize = 30f
//        text!!.setTextColor(resources.getColor(R.color.colorAccent))
        setIma(img)
        when (tab.position) {
            0->{text.setTextColor(resources.getColor(R.color.colorNews))
                ll_bg.setBackgroundResource(R.mipmap.bg02)
            }
            1->{text.setTextColor(resources.getColor(R.color.colorKaoqi))
                ll_bg.setBackgroundResource(R.mipmap.bg02)
            }
            2->{text.setTextColor(resources.getColor(R.color.colorHome))
                ll_bg.setBackgroundResource(R.mipmap.bg)
            }
            3->{text.setTextColor(resources.getColor(R.color.colorBanji))
                ll_bg.setBackgroundResource(R.mipmap.bg02)
            }
            4->{text.setTextColor(resources.getColor(R.color.colorPhoto))
                ll_bg.setBackgroundResource(R.mipmap.bg02)
            }
        }
    }

    var model:FActivityModel?=null
    var homeReceiver:AHomeReceiver?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar!!.hide()
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        window.setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        setContentView(R.layout.activity_main2)
//        Log.e("ATG","   "+android.os.Build.SERIAL)
        val add=AddData()
        add.addCardNum("test1", "3428661647", 0)
        add.addCardNum("test2", "1907098144", 0)
        add.addCardNum("test3", "1180779457", 0)
        add.addCardNum("test4", "1136897088", 0)
        add.addCardNum("test5", "2157230741", 0)
        add.addCardNum("test6", "1136881488", 0)
        add.addCardNum("test7", "1068912667", 0)
        val locationUtlis = LocationUtlis(applicationContext)
        model=FActivityModel()
        locationUtlis.Location()
        tv_SchName.text=model!!.schName
        tv_SchName.setOnClickListener(this)
        // 动态注册广播
        homeReceiver= AHomeReceiver()
        registerReceiver(homeReceiver, filter())

//        getNamePwd()
        setTab()
        setItem()
        tab.addOnTabSelectedListener(this)
//        tv_ClassName!!.setOnClickListener(this)
        viewpager!!.currentItem =2
        viewpager!!.offscreenPageLimit=5
//        DialogUtlis.showStudentDialog(this)

//        tv_ClassName.text=mainModel!!.className()
//        tv_Day.text=ClassCalendar.getStringDay()
        arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, initialList)
        lv_debug.adapter = arrayAdapter
        initIdNumber()
        val intent = Intent(applicationContext, LocalService::class.java)
        startService(intent)
        val intent1 = Intent(applicationContext, RemoteService::class.java)
        startService(intent1)
        val timer = Timer()
        timer.schedule(object : TimerTask() {

            override fun run() {
                runOnUiThread {
                    tbCard.requestFocus()
                }
            }
        }, 10000, 4000)

    }

    private fun setTab(){
        //设置tab的模式
        tab.tabMode=TabLayout.MODE_FIXED
        /**
         * 第一种：initdata()!!
         * 第二种使用listof
         */
        viewpager.adapter= KotlinPagerAdapter(initData(),supportFragmentManager)
        //让tab和viewpager关联起来
        tab.setupWithViewPager(viewpager)
    }
    private fun initIdNumber() {
        tbCard.requestFocus()
        tbCard.setOnEditorActionListener { _, _, _ ->
            val strCardNo = tbCard.text.toString().trim { it <= ' ' }
            Log.e("ATG", strCardNo)
            setCard(strCardNo)
            tbCard.setText("")
            intent.action = Constant.ERR
            intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+"卡号:"+strCardNo)
            sendBroadcast(intent)
            false
        }
    }
    private fun setCard(strCardNo: String) {
        val card = CardDao.queryLove(strCardNo)
        for (i in card.indices) {
            if (card[i].type == 0) {
                if (bl_debug) {
                    initialList.add(0, ClassCalendar.getStringtHour() + " 设备号:" + android.os.Build.SERIAL)
                    arrayAdapter!!.notifyDataSetChanged()
                    lv_debug.visibility = View.VISIBLE
                    bl_debug = false
                } else {
                    lv_debug.visibility = View.GONE
                    bl_debug = true
                }
            }else if(card[i].type==1){
                if(Constant.isTS){
                    val cardStudent = card[i].cardStudent
                    setSign(cardStudent, 3)
//                    cardStudent = card[i].cardStudent
//                    val intent = Intent(this@Main2Activity, FaceTrackingActivity::class.java)
//                    intent.putExtra("student", card[i].cardStudent.card_no)
//                    startActivity(intent)
                }else{
                    cardStudent = card[i].cardStudent
                    val intent = Intent(this@Main2Activity, FaceTrackingActivity::class.java)
                    intent.putExtra("student", card[i].cardStudent.card_no)
                    startActivity(intent)
                }
            }
        }
    }

    internal var intent = Intent()
    private fun setSign(cardStudent: CardStudent, type: Int) {
        val sign = StudentSign(cardStudent.id, ClassCalendar.getStringMinuts(),ClassCalendar.getCardtime(), type, ClassCalendar.getCardtime(), cardStudent.card_no,"")
        CardDao.insertSign(sign)
        DialogUtlis.showStudentDialog(this@Main2Activity,cardStudent.student_url)
        intent.action = Constant.ERR
        intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+"打卡成功:"+cardStudent.card_no)
        sendBroadcast(intent)
    }
    /**
     * 设置tabitem
     * */
    private fun setItem() {
        tab.getTabAt(0)?.customView=getTabView(0)
        tab.getTabAt(1)?.customView=getTabView(1)
        tab.getTabAt(2)?.customView=getTabView(2)
        tab.getTabAt(3)?.customView=getTabView(3)
        tab.getTabAt(4)?.customView=getTabView(4)
    }

    private fun setIma1(image: ImageView) {
        val para: ViewGroup.LayoutParams = image.layoutParams
        para.height = 90
        para.width = 90
        image.layoutParams = para
    }
    private fun setIma(image: ImageView) {
        val para: ViewGroup.LayoutParams = image.layoutParams
        para.height = 120
        para.width = 120
        image.layoutParams = para
    }
    /**
     * fragment 添加到集合中
     *  使用listof 代替
     * */
    private fun initData() : ArrayList<Fragment> {
        val mList = ArrayList<Fragment>()
        val tab1 = Tab1Fragment()
        val tab2 = TabJJFragment()
        val tab3 = TabHomeFragment()
        val tab4 = TabRongYuFragment()
        val tab5 = TabPhotoFragment()
        mList.add(tab1)
        mList.add(tab2)
        mList.add(tab3)
        mList.add(tab4)
        mList.add(tab5)
        return mList
    }


    private var bl_debug = true
    var initialList: MutableList<String> = ArrayList()
    private var arrayAdapter: ArrayAdapter<*>? = null


    private fun getTabView(position: Int): View {
        val view = LayoutInflater.from(this).inflate(R.layout.tab_item, null)
//        val iv_head = view.findViewById(R.id.tab_item_text) as TextView
        val iv_head=view.findViewById<TextView>(R.id.tab_item_text)
        val im=view.findViewById<ImageView>(R.id.image)
//        val im = view.findViewById(R.id.image) as ImageView
        //我们可以给库函数 arrayOf() 传递每一项的值来创建Array，arrayOf(1, 2, 3) 创建了一个[1, 2, 3] 这样的数组
        val image = arrayOf(R.mipmap.news,R.mipmap.kaoqin,R.mipmap.home,R.mipmap.banji,R.mipmap.photo)
        val list=listOf("校园资讯","校园简介","首页","学校荣誉","学校相册")
        iv_head.text=list[position]
        im.imageResource=image[position]

        /**
         * 不建议使用这种方式 我刚开始用的是这种  用这种它显示的都是第四个字符串tab4
         * */
//        val asc = Array(4,{"tab1";"tab2";"tab3";"tab4"})
//        iv_head.text=asc[position]
        return view
    }



    private var bt_close: Button?=null
    private var dialog: AlertDialog? = null
    @Throws(PackageManager.NameNotFoundException::class)
    private fun showLoginDialog() {
        val inflater = layoutInflater
        val view = inflater
                .inflate(R.layout.dialog_login, null)

        bt_close = view.findViewById(R.id.bt_close)
        bt_close!!.setOnClickListener(this)
        val tv_versionName = view.findViewById<TextView>(R.id.tv_versionName)
        tv_versionName.text = "当前版本：" + APPUtlis.packageMas(this)
        dialog = AlertDialog.Builder(this).create()
        dialog!!.setCancelable(false)
        APPUtlis.backgroundAlpha(this, 0.06f)
        dialog!!.setView(view)
        dialog!!.show()
    }

    /**
     * 广播类
     */
    inner class AHomeReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            when (action) {
                Constant.ERR -> {
                    val err = intent.getStringExtra(Constant.ERR)
                    initialList.add(0, err)
                    arrayAdapter!!.notifyDataSetChanged()
                }
                Constant.SCHNAME->{
                    tv_SchName.text=model!!.schName
                }
                Constant.SCHBANNER->{
                    Log.e("ATG","进来跳转")
                    viewpager!!.currentItem =4
                }
                Constant.SCHARTICLR->{
                    Log.e("ATG","进来跳转1")
//                    val str= intent.getStringExtra(Constant.SCHARTICLR)
                    viewpager!!.currentItem =0
                    val position= intent.getIntExtra(Constant.SCHARTICLR,0)
                    Log.e("ATG","进来跳转1"+position)
                    val intent=Intent()
                    intent.putExtra(Constant.SCHPOSTION,position)
                    intent.action=Constant.SCHPOSTION
                    sendBroadcast(intent)
                }
            }
        }
    }
    /**
     * @return IntentFilter 广播
     */
    private fun filter(): IntentFilter {
        val filter = IntentFilter()
        filter.addAction(Constant.ERR)//登录
        filter.addAction(Constant.SCHNAME)//登录
        filter.addAction(Constant.SCHBANNER)//登录
        filter.addAction(Constant.SCHARTICLR)
        return filter
    }
}
